package com.scnu.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scnu.edu.entity.Actor;
import com.scnu.edu.entity.Movie;
import com.scnu.edu.entity.MovieActor;
import com.scnu.edu.mapper.ActorMapper;
import com.scnu.edu.mapper.MovieActorMapper;
import com.scnu.edu.mapper.MovieMapper;
import com.scnu.edu.service.ActorService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActorServiceImpl extends ServiceImpl<ActorMapper, Actor> implements ActorService {
    
    @Resource
    private MovieMapper movieMapper;
    
    @Resource
    private MovieActorMapper movieActorMapper;


    @Override
    public List<Actor> findActorsByMovieId(Long id) {
        // 先查询关联表获取演员ID列表
        LambdaQueryWrapper<MovieActor> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(MovieActor::getActorId)
               .eq(MovieActor::getMovieId, id);
        List<MovieActor> relations = movieActorMapper.selectList(wrapper);
        
        // 提取演员ID列表
        List<Long> actorIds = relations.stream()
            .map(MovieActor::getActorId)
            .collect(Collectors.toList());
        
        if (actorIds.isEmpty()) {
            return Collections.emptyList();
        }
        
        // 查询演员信息
        LambdaQueryWrapper<Actor> actorWrapper = new LambdaQueryWrapper<>();
        actorWrapper.in(Actor::getId, actorIds)
                   .orderByAsc(Actor::getName);
        return baseMapper.selectList(actorWrapper);
    }
}